﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InvStorageController : ControllerBase
    {
        private readonly inv_StorageService inv_storageS;
        private readonly MyDbContext myDbContext;
        public InvStorageController(MyDbContext myDb, inv_StorageService inv_storageService)
        {
            myDbContext = myDb;
            inv_storageS = inv_storageService;
        }

        //其他入库查询
        [HttpGet]
        public async Task<IActionResult> Query()
        {
            var warehouse = await inv_storageS.Query();
            if (warehouse != null)
            {
                return Ok(warehouse);
            }
            else
            {
                return NotFound("404");
            }
        }

        //其他入库添加
        [HttpPost]
        public async Task<IActionResult> AddStorage(inv_Storage inv_storage)
        {
            if (ModelState.IsValid)
            {
                int result = await inv_storageS.Add(inv_storage);
                if (result > 0)
                {
                    return Ok("添加成功！");
                }
                else
                {
                    return BadRequest("添加失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //其他入库修改
        [HttpPut]
        public async Task<IActionResult> StorageUpdate(inv_Storage inv_storage)
        {
            if (ModelState.IsValid)
            {
                int result = await inv_storageS.Update(inv_storage);
                if (result > 0)
                {
                    return Ok("修改成功！");
                }
                else
                {
                    return BadRequest("修改失败！");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //其他入库删除
        [HttpDelete("{ow_id}")]
        public async Task<IActionResult> StorageDelete(int ow_id)
        {
            int result = await inv_storageS.Delete(ow_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }


        //分页 
        [HttpGet]
        public ActionResult<FenYe<inv_Storage>> GetFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "ow_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "inv_Storage"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<inv_Storage>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<inv_Storage> fenYe = new FenYe<inv_Storage>()
                {
                    StorageData = result,
                    Rows = row,
                };

                if (fenYe.StorageData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }

        //查询字典--物品属性
        [HttpGet]
        public async Task<IActionResult> GetAttribute()
        {
            var dic = await inv_storageS.GetAttribute();
            var dict = dic.Where(w => w.dd_type == "type_goods").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询物品名称
        [HttpGet]
        public async Task<IActionResult> GetImage(string where)
        {
            var del = await inv_storageS.GetImage();
            var data = del.Where(w => w.di_type == where).ToList();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询物品名称
        [HttpGet]
        public async Task<IActionResult> GetModel(string where)
        {
            var del = await inv_storageS.GetModel();
            var data = del.Where(w => w.di_name == where).ToList();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询字典--单位
        [HttpGet]
        public async Task<IActionResult> GetUnit()
        {
            var dic = await inv_storageS.GetUnit();
            var dict = dic.Where(w => w.dd_type == "type_unit").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }
        //查询仓库
        [HttpGet]
        public async Task<IActionResult> GetWarehouse()
        {
            var data = await inv_storageS.GetWarehouse();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }


        /// <summary>
        /// 物品入库审核
        /// </summary>
        /// <param name="ow_id"></param>
        /// <returns></returns>
        [HttpPost("{ow_id}")]
        public async Task<IActionResult> AuditInv(int ow_id)
        {
            // 从数据库中获取入库单
            var storage = await myDbContext.inv_Storage
                .FirstOrDefaultAsync(s => s.ow_id == ow_id);

            // 如果入库单不存在或已经被逻辑删除，则返回错误信息
            if (storage == null || storage.IsDeleted)
            {
                return NotFound("未找到对应的数据");
            }
            if (storage.ow_audit==true)
            {
                return BadRequest("该订单已进行了入库，不能再进行审核");
            }
            try
            {
                // 审核入库单
                storage.ow_audit = true;

                // 保存更改到数据库
                await myDbContext.SaveChangesAsync();

                return Ok("审核成功，库存已更新");
            }
            catch (DbUpdateException ex)
            {
                return StatusCode(500, "审核失败，数据库更新异常：" + ex.Message);
            }
        }

    }
}
